#include "TcpServer.hpp"
#include "HttpProtocol.hpp"
#include "Session.hpp"

std::string SuffixToDesc(const std::string &suffix)
{
    if (suffix == ".html")
        return "text/html";
    else if (suffix == ".png")
        return "image/png";
    else if (suffix == ".jpg")
        return "image/jpeg";
    else
        return "text/html";
}

std::string CodetoDesc(int code)
{
    switch (code)
    {
    case 200:
        return "OK";
    case 301:
        return "Moved Permanently";
    case 307:
        return "Temporary Redirect";
    case 403:
        return "Forbidden";
    case 404:
        return "Not Found";
    case 500:
        return "Internal Server Error";
    default:
        return "Unknown";
    }
}

std::string HandlerRequest(std::string &request)
{
    std::cout << request << std::endl;
    HttpProtocol::HttpRequest req;
    req.Deserialize(request);
    req.Parse();
    req.DebugPrint();
    std::string content = req.GetFileContent();

    int code = 200;
    if (content.empty())
    {
        code = 404;
        content = req.Get404();
    }

    // code = 307;
    HttpProtocol::HttpResponse resp;
    // if (req.GetUrl() == "/resigster")
    // {
    //     // username;passwd
    //     std::string sessionid = onlineuser.AddSession(user, passwd);
    //     std::string session = "Set-Cookie: sessionid=" + sessionid;
    //     resp.AddHeader(session);
    // }
    // if (req.GetUrl() == "/login")
    // {
    //     // username;passwd
    //     std::string sessionid;
    //     if (onlineuser.SearchSession(sessionid))
    //         // .....;
    //         resp.AddHeader(session);
    // }
    resp.SetCode(code);
    resp.SetDesc(CodetoDesc(code));
    resp.MakeStatusLine();
    std::string content_len_str = "Content-Length: " + std::to_string(content.size());
    resp.AddHeader(content_len_str);
    std::string content_type_str = "Content-Type: " + SuffixToDesc(req.GetSuffix());
    resp.AddHeader(content_type_str);
    std::string namecookie = "Set-Cookie: name=zhangsan";
    resp.AddHeader(namecookie);
    std::string passwdcookie = "Set-Cookie: password: 123456789";
    resp.AddHeader(passwdcookie);

    // std::string location_str = "Location: https://www.bilibili.com/"; // 307临时重定向
    // resp.AddHeader(location_str);

    resp.AddContent(content);
    return resp.Serialize();
}

int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        std::cout << "Usage: " << argv[0] << " ServerPort" << std::endl;
        return 0;
    }
    uint16_t port = std::stoi(argv[1]);
    TcpServer ts(port, HandlerRequest);
    ts.Loop();
    return 0;
}